package com.csun.cmny.provider.controller;


import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.csun.cmny.config.properties.CmnyProperties;
import com.csun.cmny.core.annotation.ValidateAnnotation;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.model.constant.OldInConstant;
import com.csun.cmny.provider.model.domain.OmcContract;
import com.csun.cmny.provider.model.dto.contract.ContractQueryDto;
import com.csun.cmny.provider.model.dto.contract.ContractSaveDto;
import com.csun.cmny.provider.model.dto.contract.ContractUpdateDto;
import com.csun.cmny.provider.model.vo.RpcRoleVo;
import com.csun.cmny.provider.model.vo.contract.ContractVo;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.OmcContractService;
import com.csun.cmny.provider.service.UacRpcService;
import com.csun.cmny.util.PublicUtil;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import com.github.pagehelper.PageInfo;
import com.netflix.client.ClientException;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping(value = "/omcContract", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class OmcContractController extends BaseController {

    @Resource
    private CmnyMessageSource cmnyMessageSource;

    @Resource
    private OmcContractService omcContractService;

    @Resource
    private UacRpcService uacRpcService;




    @ValidateAnnotation
    @ApiOperation(httpMethod = "POST", value = "新增合同")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Wrapper addOmcContract(@RequestBody @Valid ContractSaveDto contractSaveDto, BindingResult br) throws ParseException {
        //校验合同日期是否合规
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date start = sdf.parse(contractSaveDto.getStartDate());
        Date endDate = sdf.parse(contractSaveDto.getEndDate());
        if(endDate.before(start)){

            return WrapMapper.wrap(Wrapper.ERROR_CODE,cmnyMessageSource.getMessage("contract.startDate.error", null));

        }

        //校验此客户是否已经签过合同
        OmcContract contract = new OmcContract();
        contract.setOldIdCard(contractSaveDto.getOldIdCard());
        contract.setContractState(0);
        contract.setGroupId(getLoginAuthDto().getGroupId());

        List<OmcContract> select = omcContractService.select(contract);
        if(PublicUtil.isNotEmpty(select)){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,cmnyMessageSource.getMessage("contract.oldMan.repeat",null));

        }

        //新增合同
        OmcContract omcContract = new OmcContract();

        BeanUtils.copyProperties(contractSaveDto,omcContract);

        omcContract.setGroupId(getLoginAuthDto().getGroupId());
        omcContract.setOperator(getLoginAuthDto().getUserName());
        omcContract.setUserId(getLoginAuthDto().getUserId());
        int relust = omcContractService.save(omcContract);


        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),relust);
    }

    @ValidateAnnotation
    @ApiOperation(httpMethod = "POST", value = "修改合同")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Wrapper updateContract(@RequestBody @Valid ContractUpdateDto contractUpdateDto, BindingResult br) throws ParseException {

        //校验合同日期是否合规
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date start = sdf.parse(contractUpdateDto.getStartDate());
        Date endDate = sdf.parse(contractUpdateDto.getEndDate());
        if(endDate.before(start)){

            return WrapMapper.wrap(Wrapper.ERROR_CODE,cmnyMessageSource.getMessage("contract.startDate.error", null));

        }

        //校验合同是否存在
        OmcContract omcContract = omcContractService.selectByKey(contractUpdateDto.getId());
        if(PublicUtil.isEmpty(omcContract)){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,cmnyMessageSource.getMessage("contract.null", null));
        }


        //修改合同信息
        OmcContract omcContract1 = new OmcContract();
        BeanUtils.copyProperties(contractUpdateDto,omcContract1);
        int relust = omcContractService.update(omcContract1);



        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),relust);
    }

    @ValidateAnnotation
    @ApiOperation(httpMethod = "POST", value = "合同信息分页查询")
    @RequestMapping(value = "/select", method = RequestMethod.POST)
    public Wrapper selectContract(@RequestBody @Valid ContractQueryDto contractQueryDto, BindingResult br) throws ParseException {

        contractQueryDto.setGroupId(getLoginAuthDto().getGroupId());

        // 获取当前用户角色
        List<RpcRoleVo> roleVoList = uacRpcService.queryRoleListByUserId(getLoginAuthDto().getUserId());

        //如果角色是销售员,那么只能看自己录入的信息
        for (RpcRoleVo rpcRoleVo : roleVoList) {
            String roleCode = rpcRoleVo.getRoleCode();
            if(roleCode.equals(OldInConstant.SALESMAN)){
                contractQueryDto.setUserId(getLoginAuthDto().getUserId());
            }
        }


        List<ContractVo> list=omcContractService.selectContract(contractQueryDto);

        Date theDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddd");
        long  remindDate= theDate.getTime() + ((long) 30 * 24 * 60 * 60 * 1000);

        OmcContract omcContract1 = new OmcContract();
        omcContract1.setContractState(0);
        omcContract1.setGroupId(getLoginAuthDto().getGroupId());
        List<OmcContract> omcContracts = omcContractService.select(omcContract1);
        for (OmcContract omcContract : omcContracts) {
            //设定为合同过期状态
            if(sdf.parse(omcContract.getEndDate()).before(theDate)){

                omcContract.setContractState(3);
                omcContractService.update(omcContract);
            }
            //给即将到期的合同老人发送短信
            if(omcContract.getMsgState()==0&&sdf.parse(omcContract.getEndDate()).getTime()<remindDate){
                try {

                    SendSmsResponse response = MessDemo.sendSms(omcContract);
                    //将该客户标记为已经发送短信状态
                    if(response.getCode() != null && response.getCode().equals("OK")){
                        omcContract.setMsgState(1);
                        omcContractService.update(omcContract);
                    }
                } catch (com.aliyuncs.exceptions.ClientException e) {
                    e.printStackTrace();
                }


            }
        }


         //标注是否是本人的合同
            for (ContractVo contractVo : list) {
                if(!contractVo.getUserId().equals(getLoginAuthDto().getUserId())){
                    contractVo.setIsMy(1);
                }
            }


        PageInfo<ContractVo> pageInfo = new PageInfo<>(list);


        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),pageInfo);
    }

    @ValidateAnnotation
    @ApiOperation(httpMethod = "POST", value = "续签合同")
    @RequestMapping(value = "/renewContract", method = RequestMethod.POST)
    public Wrapper renewContract(@RequestBody @Valid ContractSaveDto contractSaveDto, BindingResult br) throws ParseException {

        //校验合同日期是否合规
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date start = sdf.parse(contractSaveDto.getStartDate());
        Date endDate = sdf.parse(contractSaveDto.getEndDate());
        if(endDate.before(start)){

            return WrapMapper.wrap(Wrapper.ERROR_CODE,cmnyMessageSource.getMessage("contract.startDate.error", null));

        }


        OmcContract contract = new OmcContract();
        contract.setOldIdCard(contractSaveDto.getOldIdCard());
        contract.setContractState(0);
        contract.setGroupId(getLoginAuthDto().getGroupId());

        List<OmcContract> select = omcContractService.select(contract);
        //校验此客户是否已经签过合同
        if(PublicUtil.isEmpty(select)){
            return WrapMapper.wrap(Wrapper.ERROR_CODE,cmnyMessageSource.getMessage("contract.oldMan.isnull", null));
        }
        //校验合同生效日期是否合规
        Date starts = sdf.parse(contractSaveDto.getStartDate());
        Date endDates = sdf.parse(select.get(0).getEndDate());
        if(!endDates.before(starts)){

            return WrapMapper.wrap(Wrapper.ERROR_CODE,cmnyMessageSource.getMessage("contract.date.error", null));

        }


        //新增合同
        OmcContract omcContract = new OmcContract();

        BeanUtils.copyProperties(contractSaveDto,omcContract);

        omcContract.setGroupId(getLoginAuthDto().getGroupId());
        omcContract.setOperator(getLoginAuthDto().getUserName());
        int relust = omcContractService.save(omcContract);



        return WrapMapper.wrap(Wrapper.SUCCESS_CODE,cmnyMessageSource.getMessage("operation.success", null),relust);
    }




}
